{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-19T11:03:48.904730Z",
     "start_time": "2020-03-19T11:03:48.293439Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import warnings\n",
    "import os\n",
    "from tqdm import tqdm\n",
    "from sklearn import preprocessing, metrics\n",
    "import lightgbm as lgb\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from joblib import Parallel, delayed\n",
    "\n",
    "%matplotlib inline\n",
    "\n",
    "pd.set_option('display.max_columns', None)\n",
    "pd.set_option('display.max_rows', None)\n",
    "\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-19T11:03:48.908869Z",
     "start_time": "2020-03-19T11:03:48.906472Z"
    }
   },
   "outputs": [],
   "source": [
    "train_path = './raw_data/eleme_round1_train_20200313'\n",
    "test_path = './raw_data/eleme_round1_testA_20200313'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-19T11:03:48.992499Z",
     "start_time": "2020-03-19T11:03:48.910145Z"
    }
   },
   "outputs": [],
   "source": [
    "courier_list = []\n",
    "# courier 数据\n",
    "for f in os.listdir(os.path.join(train_path, 'courier')):\n",
    "    date = f.split('.')[0].split('_')[1]\n",
    "    df = pd.read_csv(os.path.join(train_path, 'courier', f))\n",
    "    df['date'] = date\n",
    "    courier_list.append(df)\n",
    "\n",
    "for f in os.listdir(os.path.join(test_path, 'courier')):\n",
    "    date = f.split('.')[0].split('_')[1]\n",
    "    df = pd.read_csv(os.path.join(test_path, 'courier', f))\n",
    "    df['date'] = date\n",
    "    courier_list.append(df)\n",
    "\n",
    "df_courier = pd.concat(courier_list, sort=False)\n",
    "df_courier.to_pickle('./temp/courier.plk')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-19T11:03:49.759178Z",
     "start_time": "2020-03-19T11:03:48.993787Z"
    }
   },
   "outputs": [],
   "source": [
    "order_list = []\n",
    "# order 数据\n",
    "for f in os.listdir(os.path.join(train_path, 'order')):\n",
    "    date = f.split('.')[0].split('_')[1]\n",
    "    df = pd.read_csv(os.path.join(train_path, 'order', f))\n",
    "    df['date'] = date\n",
    "    order_list.append(df)\n",
    "\n",
    "for f in os.listdir(os.path.join(test_path, 'order')):\n",
    "    date = f.split('.')[0].split('_')[1]\n",
    "    df = pd.read_csv(os.path.join(test_path, 'order', f))\n",
    "    df['date'] = date\n",
    "    order_list.append(df)\n",
    "\n",
    "df_order = pd.concat(order_list, sort=False)\n",
    "df_order.to_pickle('./temp/order.plk')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-19T11:04:25.926110Z",
     "start_time": "2020-03-19T11:03:49.760577Z"
    }
   },
   "outputs": [],
   "source": [
    "distance_list = []\n",
    "# distance 数据\n",
    "for f in os.listdir(os.path.join(train_path, 'distance')):\n",
    "    date = f.split('.')[0].split('_')[1]\n",
    "    df = pd.read_csv(os.path.join(train_path, 'distance', f))\n",
    "    df['date'] = date\n",
    "    distance_list.append(df)\n",
    "\n",
    "for f in os.listdir(os.path.join(test_path, 'distance')):\n",
    "    date = f.split('.')[0].split('_')[1]\n",
    "    df = pd.read_csv(os.path.join(test_path, 'distance', f))\n",
    "    df['date'] = date\n",
    "    distance_list.append(df)\n",
    "\n",
    "df_distance = pd.concat(distance_list, sort=False)\n",
    "df_distance['group'] = df_distance['date'].astype(\n",
    "    'str') + df_distance['courier_id'].astype('str') + df_distance['wave_index'].astype('str')\n",
    "df_distance.to_pickle('./temp/distance.plk')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-19T11:04:25.937956Z",
     "start_time": "2020-03-19T11:04:25.929096Z"
    }
   },
   "outputs": [],
   "source": [
    "# 后 55% 为待预测行为\n",
    "ratio = 0.55\n",
    "\n",
    "\n",
    "def read_feat(df):\n",
    "    label_list = []\n",
    "    history_list = []\n",
    "    type = df['type'].values[0]\n",
    "\n",
    "    # 划分数据集\n",
    "    groups = df.groupby(['courier_id', 'wave_index'])\n",
    "    for name, group in tqdm(groups):\n",
    "        if type == 'train':\n",
    "            label_data = group.tail(int(group.shape[0] * ratio))\n",
    "            history_data = group.drop(label_data.index)\n",
    "\n",
    "            if label_data.shape[0] < 3:\n",
    "                continue\n",
    "            else:\n",
    "                # 第一个数据为正样本，其余为负样本\n",
    "                label_data['target'] = 0\n",
    "                label_data.reset_index(drop=True, inplace=True)\n",
    "                label_data.loc[0, 'target'] = 1\n",
    "                label_list.append(label_data)\n",
    "                history_list.append(history_data)\n",
    "        else:\n",
    "            label_data = group[group['expect_time'] == 0]\n",
    "            history_data = group.drop(label_data.index)\n",
    "\n",
    "            label_data['target'] = None\n",
    "            label_list.append(label_data)\n",
    "            history_list.append(history_data)\n",
    "\n",
    "    return pd.concat(label_list, sort=False), pd.concat(history_list, sort=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-19T11:04:57.252940Z",
     "start_time": "2020-03-19T11:04:25.940141Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 35/35 [00:13<00:00,  2.53it/s]\n"
     ]
    }
   ],
   "source": [
    "df_actions = []\n",
    "for f in os.listdir(os.path.join(train_path, 'action')):\n",
    "    date = f.split('.')[0].split('_')[1]\n",
    "    df = pd.read_csv(os.path.join(train_path, 'action', f))\n",
    "    df['date'] = date\n",
    "    df['type'] = 'train'\n",
    "    df_actions.append(df)\n",
    "\n",
    "for f in os.listdir(os.path.join(test_path, 'action')):\n",
    "    date = f.split('.')[0].split('_')[1]\n",
    "    df = pd.read_csv(os.path.join(test_path, 'action', f))\n",
    "    df['date'] = date\n",
    "    df['type'] = 'test'\n",
    "    df_actions.append(df)\n",
    "\n",
    "res = Parallel(n_jobs=12)(delayed(read_feat)(df) for df in tqdm(df_actions))\n",
    "df_feature = [item[0] for item in res]\n",
    "df_history = [item[1] for item in res]\n",
    "\n",
    "df_feature = pd.concat(df_feature, sort=False)\n",
    "df_history = pd.concat(df_history, sort=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-19T11:04:57.814938Z",
     "start_time": "2020-03-19T11:04:57.254610Z"
    }
   },
   "outputs": [],
   "source": [
    "df_feature['group'] = df_feature['date'].astype(\n",
    "    'str') + df_feature['courier_id'].astype('str') + df_feature['wave_index'].astype('str')\n",
    "df_history['group'] = df_history['date'].astype(\n",
    "    'str') + df_history['courier_id'].astype('str') + df_history['wave_index'].astype('str')\n",
    "df_feature['target'] = df_feature['target'].astype('float')\n",
    "df_feature['id'] = range(df_feature.shape[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-19T11:04:57.831102Z",
     "start_time": "2020-03-19T11:04:57.816186Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>courier_id</th>\n",
       "      <th>wave_index</th>\n",
       "      <th>tracking_id</th>\n",
       "      <th>courier_wave_start_lng</th>\n",
       "      <th>courier_wave_start_lat</th>\n",
       "      <th>action_type</th>\n",
       "      <th>expect_time</th>\n",
       "      <th>date</th>\n",
       "      <th>type</th>\n",
       "      <th>target</th>\n",
       "      <th>group</th>\n",
       "      <th>id</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>10007871</td>\n",
       "      <td>0</td>\n",
       "      <td>2100074550065333539</td>\n",
       "      <td>121.630997</td>\n",
       "      <td>39.142343</td>\n",
       "      <td>DELIVERY</td>\n",
       "      <td>1580528963</td>\n",
       "      <td>20200201</td>\n",
       "      <td>train</td>\n",
       "      <td>1.0</td>\n",
       "      <td>20200201100078710</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>10007871</td>\n",
       "      <td>0</td>\n",
       "      <td>2100074550779577850</td>\n",
       "      <td>121.630997</td>\n",
       "      <td>39.142343</td>\n",
       "      <td>PICKUP</td>\n",
       "      <td>1580529129</td>\n",
       "      <td>20200201</td>\n",
       "      <td>train</td>\n",
       "      <td>0.0</td>\n",
       "      <td>20200201100078710</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>10007871</td>\n",
       "      <td>0</td>\n",
       "      <td>2100074550779577850</td>\n",
       "      <td>121.630997</td>\n",
       "      <td>39.142343</td>\n",
       "      <td>DELIVERY</td>\n",
       "      <td>1580529444</td>\n",
       "      <td>20200201</td>\n",
       "      <td>train</td>\n",
       "      <td>0.0</td>\n",
       "      <td>20200201100078710</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>10007871</td>\n",
       "      <td>1</td>\n",
       "      <td>2100074555638285402</td>\n",
       "      <td>121.631208</td>\n",
       "      <td>39.142519</td>\n",
       "      <td>PICKUP</td>\n",
       "      <td>1580532225</td>\n",
       "      <td>20200201</td>\n",
       "      <td>train</td>\n",
       "      <td>1.0</td>\n",
       "      <td>20200201100078711</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>10007871</td>\n",
       "      <td>1</td>\n",
       "      <td>2100074554118800474</td>\n",
       "      <td>121.631208</td>\n",
       "      <td>39.142519</td>\n",
       "      <td>PICKUP</td>\n",
       "      <td>1580532227</td>\n",
       "      <td>20200201</td>\n",
       "      <td>train</td>\n",
       "      <td>0.0</td>\n",
       "      <td>20200201100078711</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   courier_id  wave_index          tracking_id  courier_wave_start_lng  \\\n",
       "0    10007871           0  2100074550065333539              121.630997   \n",
       "1    10007871           0  2100074550779577850              121.630997   \n",
       "2    10007871           0  2100074550779577850              121.630997   \n",
       "0    10007871           1  2100074555638285402              121.631208   \n",
       "1    10007871           1  2100074554118800474              121.631208   \n",
       "\n",
       "   courier_wave_start_lat action_type  expect_time      date   type  target  \\\n",
       "0               39.142343    DELIVERY   1580528963  20200201  train     1.0   \n",
       "1               39.142343      PICKUP   1580529129  20200201  train     0.0   \n",
       "2               39.142343    DELIVERY   1580529444  20200201  train     0.0   \n",
       "0               39.142519      PICKUP   1580532225  20200201  train     1.0   \n",
       "1               39.142519      PICKUP   1580532227  20200201  train     0.0   \n",
       "\n",
       "               group  id  \n",
       "0  20200201100078710   0  \n",
       "1  20200201100078710   1  \n",
       "2  20200201100078710   2  \n",
       "0  20200201100078711   3  \n",
       "1  20200201100078711   4  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_feature.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-03-19T11:04:57.984646Z",
     "start_time": "2020-03-19T11:04:57.832199Z"
    }
   },
   "outputs": [],
   "source": [
    "df_history.to_pickle('./temp/action_history.plk')\n",
    "df_feature.to_pickle('./temp/base_feature.plk')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:dm] *",
   "language": "python",
   "name": "conda-env-dm-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
